package com.lsh.netty.echo.mgspackecho;

import com.lsh.serializable.UserInfo;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

/**
 * @author ：LiuShihao
 * @date ：Created in 2021年04月12日17:18:40
 * @desc ：
 */
public class EchoClientHandler extends ChannelHandlerAdapter {

    private final int sendNuber ;


    public EchoClientHandler(int sendNuber){
        this.sendNuber = sendNuber;

    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        UserInfo[] infos =  UserInfo();
        for (UserInfo info : infos) {
            ctx.write(info);
        }
        ctx.flush();
    }

    private UserInfo[] UserInfo(){
        UserInfo[] userInfos = new UserInfo[sendNuber];
        UserInfo userInfo = null;
        for (int i = 0; i < sendNuber; i++) {
            userInfo = new UserInfo();
            userInfo.setUserID(i);
            userInfo.setUserName("ABCDEFG --->"+i);
            userInfos[i] = userInfo;
        }
        System.out.println("userInfos.length : "+userInfos.length);
        return userInfos;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg)  throws Exception{
        System.out.println("Client receive the magpack message :"+msg);
//        ctx.write(msg);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
//        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
